package MallOrderStatistics

import (
	Router2SystemConfig "gitee.com/fotomxq/weeekj_core/v5/router2/system_config"
)

type ArgsGetOrderStatistics struct {
	//组织ID
	OrgID int64 `db:"org_id" json:"orgID"`
	//用户ID
	UserID int64 `db:"user_id" json:"userID"`
}

// GetOrderStatistics 根据用户id获取订单统计数据
func GetOrderStatistics(args *ArgsGetOrderStatistics) (dataList []FieldsOrderStatistics, errCode string, err error) {
	//获取数据
	var rawList []FieldsOrderStatistics
	err = Router2SystemConfig.MainDB.Select(&rawList, "SELECT id FROM mall_order_statistics WHERE delete_at < to_timestamp(1000000) AND user_id = $1 and status = 0", args.UserID)
	if err != nil {
		return
	}
	for _, v := range rawList {
		vData := GetOrderStatisticsByID(v.ID)
		if vData.ID < 1 {
			continue
		}
		dataList = append(dataList, vData)
	}
	//反馈
	return

}

// GetOrderStatisticsByID 根据id获取数据
func GetOrderStatisticsByID(id int64) (data FieldsOrderStatistics) {
	//获取数据
	err := Router2SystemConfig.MainDB.Get(&data, "SELECT id, create_at, update_at, delete_at, org_id, user_id, order_id, order_price, des, status,pay_id FROM mall_order_statistics WHERE id = $1", id)
	if err != nil || data.ID < 1 {
		return
	}
	//反馈
	return
}

// GetOrderTotalPriceByUserID 根据用户id获取订单累计金额
func GetOrderTotalPriceByUserID(args *ArgsGetOrderStatistics) (totalPrice int64, err error) {
	err = Router2SystemConfig.MainDB.Get(&totalPrice,
		"SELECT COALESCE(SUM(order_price), 0) FROM mall_order_statistics WHERE  delete_at < to_timestamp(1000000) AND status = 0  AND user_id = $1 ",
		args.UserID)
	if err != nil {
		return
	}
	//反馈
	return
}

// GetOrderTotalPriceByPayID 根据支付订单id获取清缴信息
func GetOrderTotalPriceByPayID(payID int64) (dataList []FieldsOrderStatistics, err error) {
	//获取数据
	var rawList []FieldsOrderStatistics
	err = Router2SystemConfig.MainDB.Select(&rawList, "SELECT id FROM mall_order_statistics WHERE delete_at < to_timestamp(1000000) AND pay_id = $1 and status = 0", payID)
	if err != nil {
		return
	}
	for _, v := range rawList {
		vData := GetOrderStatisticsByID(v.ID)
		if vData.ID < 1 {
			continue
		}
		dataList = append(dataList, vData)
	}
	return
}

// GetOrderTotalPriceTotal 获取未清缴订单总金额
func GetOrderTotalPriceTotal(orgID int64) (totalPrice int64, err error) {
	err = Router2SystemConfig.MainDB.Get(&totalPrice,
		"SELECT COALESCE(SUM(order_price), 0) FROM mall_order_statistics WHERE  delete_at < to_timestamp(1000000) AND status = 0  AND org_id = $1 ",
		orgID)
	if err != nil {
		return
	}
	//反馈
	return
}
